package approve.action;


import java.util.Timer;
import java.util.TimerTask;

import nguyen.dao.ReceiverDocumentDAO;
import project.active.L_list_subprolistmenu;
import project.active.ListProjectManager;
import project.active.LogoutActivity;
import project.active.Newproject;
import project.active.Projectlist;
import project.active.Projectlist_tc;
import model.pojo.Employee;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

public class MainFrame extends TabActivity {
	static int soluong=0;
	TextView logout,username,report;
	String lang = "EN",database;
	Bundle language;
	Employee emp= new Employee();
	public String getDatabase() {
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			database = extras.getString("database");
		}
		return database;
	}
	ListView list;
	
	Timer timer=new Timer();
	NotificationManager mNotificationManager=null;
	private int SIMPLE_NOTFICATION_ID;

	L_list_subprolistmenu admenu;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainframe);
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		language = getIntent().getExtras().getBundle(getLang());
		emp=(Employee) getIntent().getExtras().get("em");
		showNotificationMessage();
		Resources res = getResources();
	    TabHost tabHost = getTabHost();
	    TabHost.TabSpec spec;
	    spec = tabHost.newTabSpec("approve").setIndicator(language.getString("ac_approved"),
	                      res.getDrawable(R.drawable.ic_tab_artists));
	    spec.setContent(new TabHost.TabContentFactory() {
			

			public View createTabContent(String tag) {
				// TODO Auto-generated method stub
				ListView listapprove = new ListView(MainFrame.this);
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainFrame.this,android.R.layout.simple_list_item_1,listAllApprove(getLang()));
				listapprove.setAdapter(adapter); 
				listapprove.setOnCreateContextMenuListener(MainFrame.this);
				OnItemClickListener listener = new OnItemClickListener() {


					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						String item = arg0.getItemAtPosition(arg2).toString();
						if(item.equals("New Document") || item.equals("문서 작성") ||item.equals("Tạo Văn Bản")){
							Intent intent = new Intent(MainFrame.this,ApporoveNewActivity.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}else if(item.equals("Pending Document")|| item.equals("결재대기문서") ||item.equals("Văn bản chờ duyệt")){
							Intent intent = new Intent(MainFrame.this,Re_PendingDocument.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}else if(item.equals("Not approved document")|| item.equals("미결재문서 ") ||item.equals("Văn bản chưa duyệt")){
							Intent intent = new Intent(MainFrame.this,Re_NotApprovedDocument.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
							
						}else if(item.equals("Approved document")|| item.equals("결재완료문서") ||item.equals("Văn bản đã duyệt")){
							Intent intent = new Intent(MainFrame.this,Re_ApprovedDocument.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}else if(item.equals("Decline document")|| item.equals("반려문서") ||item.equals("Văn bản bị từ chối")){
							Intent intent = new Intent(MainFrame.this,Re_DeclineDocument.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}else if(item.equals("Meeting document pending")|| item.equals("내가 받은 회의록") ||item.equals("Văn bản cuộc họp nhận")){
							Intent intent = new Intent(MainFrame.this,Re_MeetingDocumentPendding.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
//						}else if(item.equals("Meeting document sending")|| item.equals("내가 올린 회의록") ||item.equals("Văn bản cuộc họp gửi")){
//							
						}else if(item.equals("Reference document")|| item.equals("참조문서함") ||item.equals("Văn bản tham khảo")){
							Intent intent = new Intent(MainFrame.this,Re_ReferenceDocument.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						
						/*Start MaiMai*/
						}else if(item.equals("My Document sending")|| item.equals("상신문서i") ||item.equals("Văn bản đã gởi")){
							Intent intent = new Intent(MainFrame.this,My_App_DocumentSending.class);
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);

						}else if(item.equals("My Saved document")|| item.equals("임시보관i") ||item.equals("Văn bản lưu")){
							Intent intent = new Intent(MainFrame.this,My_App_SavedDocument.class);
							//System.out.println(lang +"--------- "+ getDatabase());
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}
						else if(item.equals("My Approved document")|| item.equals("결재완료문서i") ||item.equals("Văn bản duyệt")){
							Intent intent = new Intent(MainFrame.this,My_App_ApprovedDocument.class);
							//System.out.println(lang +"--------- "+ getDatabase());
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}
						else if(item.equals("My Decline document")|| item.equals("반려문서i") ||item.equals("Văn bản từ chối")){
							Intent intent = new Intent(MainFrame.this,My_App_DeclineDocument.class);
							//System.out.println(lang +"--------- "+ getDatabase());
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}
						else if(item.equals("My Meeting document sending")|| item.equals("내가 올린 회의록i") ||item.equals("Văn bản họp gửi")){
							Intent intent = new Intent(MainFrame.this,My_App_MeetingDocumentSendding.class);
							//System.out.println(lang +"--------- "+ getDatabase());
							intent.putExtra("lang", lang);
							intent.putExtra("database", getDatabase());
							intent.putExtras(getIntent().getExtras());
							startActivityForResult(intent, 0);
						}
						else if(item.equals("Personal")|| item.equals("개인결재라인") ||item.equals("Cá nhân")){
							
						}
						/*End MaiMai*/
						else if(item.equals("Department")|| item.equals("부서") ||item.equals("Phòng Ban")){
							

							
						}else if(item.equals("Saved document")|| item.equals("임시보관") ||item.equals("Văn bản được lưu")){
							

						}
					}
					
				};
				listapprove.setOnItemClickListener(listener);
                 return listapprove;
			}
		});
	    tabHost.addTab(spec);

	    // Do the same for the other tabs
	    spec = tabHost.newTabSpec("project").setIndicator(language.getString("project"),
	                      res.getDrawable(R.drawable.ic_tab_artists));
	    spec.setContent(new TabHost.TabContentFactory() {
			

			public View createTabContent(String tag) {
				// TODO Auto-generated method stub
				ListView listproject = new ListView(MainFrame.this);
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainFrame.this,android.R.layout.simple_list_item_1,listAllProject(getLang()));
				admenu = new L_list_subprolistmenu(MainFrame.this, listAllProject(getLang()));
//				listproject.setAdapter(adapter); 
				listproject.setAdapter(admenu); 
				
				
				listproject.setOnCreateContextMenuListener(MainFrame.this);
				OnItemClickListener listenerProject = new OnItemClickListener() {
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						String item = arg0.getItemAtPosition(arg2).toString();
						if(emp.getIdrole()==1){
//							if(item.equals("새 프로젝트") || item.equals("Dự án mới") || item.equals("New Project")){
//								Intent intent=new Intent(MainFrame.this,Newproject.class);
//								intent.putExtra("lang", getLang());
//								intent.putExtra("database", getDatabase());
//								intent.putExtra("em",emp);
//								//intent.putExtra("proaction", "newpro");
//								intent.putExtras(getIntent().getExtras());
//								startActivityForResult(intent, 0);
//							}else if(item.equals("List Project") || item.equals("프로젝트 리스트") || item.equals("Danh sách dự án")){
//								Intent intent=new Intent(MainFrame.this,Projectlist.class);
//								intent.putExtra("lang", getLang());
//								intent.putExtra("database", getDatabase());
//								intent.putExtra("em",emp);
//								intent.putExtras(getIntent().getExtras());
//								startActivityForResult(intent, 1);
//							}
							if(item.equals(language.getString("new_project"))){
								Intent intent=new Intent(MainFrame.this,Newproject.class);
								intent.putExtra("lang", getLang());
								intent.putExtra("database", getDatabase());
								intent.putExtra("em",emp);
								//intent.putExtra("proaction", "newpro");
								intent.putExtras(getIntent().getExtras());
								startActivityForResult(intent, 0);
							}else if(item.equals(language.getString("ac_SUProjectList"))){
								Intent intent=new Intent(MainFrame.this,Projectlist.class);
								intent.putExtra("lang", getLang());
								intent.putExtra("database", getDatabase());
								intent.putExtra("em",emp);
								intent.putExtras(getIntent().getExtras());
								startActivityForResult(intent, 1);
							}
						}else{
							if(item.equals("List Manager") || item.equals("List mana") || item.equals("Du an quan ly")){
								Intent intent = new Intent(MainFrame.this,ListProjectManager.class);
								intent.putExtra("lang", getLang());
								intent.putExtra("database", getDatabase());
								intent.putExtra("em",emp);
								intent.putExtras(getIntent().getExtras());
								startActivityForResult(intent,0);
								
							}else if(item.equals("List Member") || item.equals("List mem") || item.equals("Du an thanh vien")){
								Intent intent=new Intent(MainFrame.this,Projectlist_tc.class);
								intent.putExtra("lang", getLang());
								intent.putExtra("database", getDatabase());
								intent.putExtra("em",emp);
								intent.putExtras(getIntent().getExtras());
								startActivityForResult(intent, 0);
							}
						}
						
					}
					
				};
				listproject.setOnItemClickListener(listenerProject );
                 return listproject;
			}
		});
	    tabHost.addTab(spec);
	    tabHost.setCurrentTab(2);
	    
	    Intent currentIntent = this.getIntent();
	    emp = (Employee)currentIntent.getSerializableExtra("em");
	    
	    showDialogMessage();
	    logout=(TextView)findViewById(R.id.logout);
		username=(TextView)findViewById(R.id.username);
		logout.setText(language.getString("Logout"));
		
		logout.setOnClickListener(listenerLogout);
		username.setText(emp.getUserName());
//		report=(TextView)findViewById(R.id.report);
//		if(ReceiverDocumentDAO.countAllNewMessage(emp.getIdemployee(), getDatabase()) == 0 || ReceiverDocumentDAO.countAllNewMessage(emp.getIdemployee(), getDatabase()) == 1){
//			report.setText( "You have" + " " + ReceiverDocumentDAO.countAllNewMessage(emp.getIdemployee(), getDatabase()) + " " + "new message");
//		}else{
//			report.setText( "You have" + " " + ReceiverDocumentDAO.countAllNewMessage(emp.getIdemployee(), getDatabase()) + " " + "new messages");
//		}
	}
	
	private OnClickListener listenerLogout=new OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
//			Intent i=new Intent(MainFrame.this, LoginActivity.class);	
			soluong=0;
			timer.cancel();
			mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
			
			Intent i=new Intent(MainFrame.this, LogoutActivity.class);
			i.putExtra("database", getDatabase());
			startActivity(i);
		}
	};

	private void showDialogMessage(){
		
		int count=rd.countAllNewMessage(emp.getIdemployee(), getDatabase());
//		if(count==0 || count==1){
//			String message="You have "+count+" new message";
//			Button btt = new Button(this);
//			btt.setText("Submit");
//			Toast.makeText(this, message, Toast.LENGTH_LONG).show();
//			
//			
//		}else{
//			String message="You have "+count+" new messages";
//			Button btt = new Button(this);
//			btt.setText("Submit");
//			Toast.makeText(this, message, Toast.LENGTH_LONG).show();
//		}
//		
		if(count <= 0){
			Toast.makeText(this, "You hav'nt new message!", Toast.LENGTH_LONG).show();
		}
		else{
			popupMessage(count);
		}
	}
	
	private void popupMessage(int count){
		AlertDialog.Builder popupmessage = new AlertDialog.Builder(this);
		popupmessage.setTitle(count + " new message");
		popupmessage.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				final Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://14.63.219.99/checkAndroidToPC.jsp?dbname="+getDatabase()+"&user="+emp.getUserName()+"&lg="+getLang()));
				startActivity(intent);
			}
		});
		popupmessage.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
		});
		// Remember, create doesn't show the dialog
		AlertDialog messDialog = popupmessage.create();
		messDialog.show();
	}

	public String getLang() {
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			lang = extras.getString("lang");
		}
		return lang;
	}

	public String[] listAllApprove(String value) {
		String[] menu = null;
		if (value.equals("EN")) {
			menu = getResources().getStringArray(R.array.approval_en);
		} else if (value.equals("KR")) {
			menu = getResources().getStringArray(R.array.approval_kr);
		} else {
			menu = getResources().getStringArray(R.array.approval_vn);
		}
		return menu;
	}
	public String[] listAllProject(String value) {
		String[] menu = null;
		if(emp.getIdrole()==1){
//			if (value.equals("EN")) {
//				menu = getResources().getStringArray(R.array.project_en_admin);
//			} else if (value.equals("KR")) {
//				menu = getResources().getStringArray(R.array.project_kr_admin);
//			} else {
//				menu = getResources().getStringArray(R.array.project_vn_admin);
//			}
			menu= new String[2];
			if(language.getString("new_project")!=null){
				menu[0]=language.getString("new_project");
			}else
				menu[0]="";
			
			if(language.getString("ac_SUProjectList")!=null){
				menu[1]=language.getString("ac_SUProjectList");
			}else
				menu[1]="";
			
		}else{
			if (value.equals("EN")) {
				menu = getResources().getStringArray(R.array.project_en_member);
			} else if (value.equals("KR")) {
				menu = getResources().getStringArray(R.array.project_kr_member);
			} else {
				menu = getResources().getStringArray(R.array.project_vn_member);
			}
		}
		
		return menu;
	}
	
	private void showNotificationMessage(){
		timer.scheduleAtFixedRate(new mainTask(), 500, 50000);
	//	
	}
	ReceiverDocumentDAO rd = new ReceiverDocumentDAO();
	private class mainTask extends TimerTask {

		@Override
		public void run() {
			mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
			final Notification notifyDetails;
			String idem = emp.getIdemployee();
			System.out.println("idem: "+idem);
			int count=rd.countAllNewMessage(idem, getDatabase());
			if(count>0){
				
//				if(count>0){
////					notifyDetails = new Notification(R.drawable.ic_launcher,
////						count + " new message", 500);
//					 notifyDetails = new Notification(R.drawable.ic_launcher,
//								count + " new message", System.currentTimeMillis());
//				}else if(count <=0){
////					notifyDetails = new Notification(R.drawable.ic_launcher,"",500);
//					notifyDetails = new Notification(R.drawable.ic_launcher,"",System.currentTimeMillis());
//					
//				}
//				else{
////					notifyDetails = new Notification(R.drawable.ic_launcher,
////							count + " new messages", 500);
//					notifyDetails = new Notification(R.drawable.ic_launcher,
//							count + " new messages", System.currentTimeMillis());
//				}
				
				if(count!=soluong){
					soluong=count;
//					notifyDetails = new Notification(R.drawable.ic_launcher,
//						count + " new message", 500);
					 notifyDetails = new Notification(R.drawable.ic_launcher,
								count + " new message", System.currentTimeMillis());
				
					 notifyDetails.defaults = Notification.DEFAULT_ALL;
						Context context = getApplicationContext();
						CharSequence contentTitle = "You have " + count + " new message";
						CharSequence contentText = "click me to view detail";
						

						Intent notifyIntent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://14.63.219.99/checkAndroidToPC.jsp?dbname="+getDatabase()+"&user="+emp.getUserName()+"&lg="+getLang()));
						
						PendingIntent intent = PendingIntent.getActivity(MainFrame.this,
								0, notifyIntent,
								android.content.Intent.FLAG_ACTIVITY_NEW_TASK);

						notifyDetails.setLatestEventInfo(context, contentTitle,
								contentText, intent);
				//
						mNotificationManager.notify(SIMPLE_NOTFICATION_ID,
								notifyDetails);
//						mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
//						
						
				}
			}
			 
		}
		
	}
}
